package com.ruoyi.web.controller.fs;

import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.annotation.Excel;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.fs.domain.*;
import com.ruoyi.fs.service.*;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.controller.tool.ExcelExporter;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 还款计划Controller
 *
 * @author hero
 * @date 2024-11-11
 */
@RestController
@RequestMapping("/fs/schedule")
public class FsCaseRepaymentScheduleController extends BaseController {
    @Autowired
    private IFsCaseRepaymentScheduleService fsCaseRepaymentScheduleService;
    @Autowired
    private IFsCaseRepaymentScheduleFileService fsCaseRepaymentScheduleFileService;
    @Autowired
    private IFsCaseRepaymentSchedulePayService fsCaseRepaymentSchedulePayService;
    @Autowired
    private IFsRepaymentStatisticService fsRepaymentStatisticService;
    @Autowired
    private IFsCaseService fsCaseService;
    @Autowired
    private IFsClientService fsClientService;
    @Autowired
    private IFsEntrustService fsEntrustService;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 查询还款计划列表
     */
    @PreAuthorize("@ss.hasPermi('fs:case:list')")
    @GetMapping("/list")
    public TableDataInfo list(FsCaseRepaymentSchedule fsCaseRepaymentSchedule) {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        List<SysRole> roles = user.getRoles();
        List<Long> roleIds = new ArrayList<>();
        for (int i = 0; i < roles.size(); i++) {
            roleIds.add(roles.get(i).getRoleId());
        }
        if (roleIds.contains(1) || roleIds.contains(2)) {

        } else if (roleIds.contains(101L)) {
            fsCaseRepaymentSchedule.setSsr(user.getUserId());
        }
        Map<Long, String> zfMap = new HashMap<>();
        List<FsEntrust> entrusts = fsEntrustService.selectFsEntrustList(new FsEntrust());
        for (int i = 0; i < entrusts.size(); i++) {
            zfMap.put(entrusts.get(i).getId(), entrusts.get(i).getName());
        }
        Map<Long, String> userMap = new HashMap<>();
        List<SysUser> users = sysUserService.selectUserList(new SysUser());
        for (int i = 0; i < users.size(); i++) {
            userMap.put(users.get(i).getUserId(), users.get(i).getNickName());
        }
        startPage();
        List<FsCaseRepaymentSchedule> list = fsCaseRepaymentScheduleService.selectFsCaseRepaymentScheduleList(fsCaseRepaymentSchedule);
        for (int i = 0; i < list.size(); i++) {
            FsCaseRepaymentSchedule schedule = list.get(i);
            FsCase fsCase = fsCaseService.selectFsCaseById(schedule.getCaseId());
            FsClient bg = fsClientService.selectFsClientById(fsCase.getBg());
            fsCase.setBgDsr(bg);
            if (fsCase.getZfid() != null) {
                fsCase.setZfName(zfMap.get(fsCase.getZfid()));
            }
            schedule.setFsCase(fsCase);
            if (schedule.getScr() != null) {
                schedule.setScrMc(userMap.get(schedule.getScr()));
            }
            List<FsCaseRepaymentScheduleFile> files = new ArrayList<>();
            FsCaseRepaymentSchedulePay payQuery = new FsCaseRepaymentSchedulePay();
            payQuery.setScheduleId(schedule.getId());
            List<FsCaseRepaymentSchedulePay> pays = fsCaseRepaymentSchedulePayService.selectFsCaseRepaymentSchedulePayList(payQuery);
            for (int j = 0; j < pays.size(); j++) {
                FsCaseRepaymentSchedulePay pay = pays.get(j);
                FsCaseRepaymentScheduleFile fileQuery = new FsCaseRepaymentScheduleFile();
                fileQuery.setPayId(pay.getId());
                List<FsCaseRepaymentScheduleFile> payFiles = fsCaseRepaymentScheduleFileService.selectFsCaseRepaymentScheduleFileList(fileQuery);
                pay.setFiles(payFiles);
                files.addAll(payFiles);
            }
            schedule.setFiles(files);
            schedule.setPays(pays);
        }
        return getDataTable(list);
    }

    /**
     * 导出还款计划列表
     */
    @PreAuthorize("@ss.hasPermi('fs:case:export')")
    @Log(title = "还款计划", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, FsCaseRepaymentSchedule fsCaseRepaymentSchedule) {
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        List<SysRole> roles = user.getRoles();
        List<Long> roleIds = new ArrayList<>();
        for (int i = 0; i < roles.size(); i++) {
            roleIds.add(roles.get(i).getRoleId());
        }
        if (roleIds.contains(1) || roleIds.contains(2)) {

        } else if (roleIds.contains(101L)) {
            fsCaseRepaymentSchedule.setSsr(user.getUserId());
        }
        Map<Long, String> zfMap = new HashMap<>();
        List<FsEntrust> entrusts = fsEntrustService.selectFsEntrustList(new FsEntrust());
        for (int i = 0; i < entrusts.size(); i++) {
            zfMap.put(entrusts.get(i).getId(), entrusts.get(i).getName());
        }
        Map<Long, String> userMap = new HashMap<>();
        List<SysUser> users = sysUserService.selectUserList(new SysUser());
        for (int i = 0; i < users.size(); i++) {
            userMap.put(users.get(i).getUserId(), users.get(i).getNickName());
        }
        List<FsCaseRepaymentSchedule> list = fsCaseRepaymentScheduleService.selectFsCaseRepaymentScheduleList(fsCaseRepaymentSchedule);
        for (int i = 0; i < list.size(); i++) {
            FsCaseRepaymentSchedule schedule = list.get(i);
            FsCase fsCase = fsCaseService.selectFsCaseById(schedule.getCaseId());
            FsClient bg = fsClientService.selectFsClientById(fsCase.getBg());
            fsCase.setBgDsr(bg);
            if (fsCase.getZfid() != null) {
                fsCase.setZfName(zfMap.get(fsCase.getZfid()));
            }
            schedule.setFsCase(fsCase);
            if (schedule.getScr() != null) {
                schedule.setScrMc(userMap.get(schedule.getScr()));
            }
            FsCaseRepaymentSchedulePay payQuery = new FsCaseRepaymentSchedulePay();
            payQuery.setScheduleId(schedule.getId());
            List<FsCaseRepaymentSchedulePay> pays = fsCaseRepaymentSchedulePayService.selectFsCaseRepaymentSchedulePayList(payQuery);
            BigDecimal yhje = BigDecimal.ZERO;
            BigDecimal dshje = BigDecimal.ZERO;
            for (int j = 0; j < pays.size(); j++) {
                FsCaseRepaymentSchedulePay pay = pays.get(j);
                if (pay.getZt() == 0) {
                    dshje = dshje.add(pay.getShje());
                }
                if (pay.getZt() == 1) {
                    yhje = yhje.add(pay.getShje());
                }
            }
            schedule.setYhje(yhje);
            schedule.setDshje(dshje);
            schedule.setPays(pays);
        }

        try {
            InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/还款计划模板.xlsx");
            ExcelExporter.exportDataToTemplateForRepaymentSchedule(response, list, inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取还款计划详细信息
     */
    @PreAuthorize("@ss.hasPermi('fs:case:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(fsCaseRepaymentScheduleService.selectFsCaseRepaymentScheduleById(id));
    }

    /**
     * 新增还款计划
     */
    @PreAuthorize("@ss.hasPermi('fs:case:add')")
    @Log(title = "还款计划", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody FsCaseRepaymentSchedule fsCaseRepaymentSchedule) {
        return toAjax(fsCaseRepaymentScheduleService.insertFsCaseRepaymentSchedule(fsCaseRepaymentSchedule));
    }

    /**
     * 修改待还
     */
    @PreAuthorize("@ss.hasPermi('fs:case:edit')")
    @Log(title = "还款计划", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody FsCaseRepaymentSchedule schedule) {
        FsCaseRepaymentSchedule old = fsCaseRepaymentScheduleService.selectFsCaseRepaymentScheduleById(schedule.getId());
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(old.getJhrq());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        FsRepaymentStatistic query = new FsRepaymentStatistic();
        query.setSsr(old.getSsr());
        query.setYear(year);
        query.setMonth(month);
        List<FsRepaymentStatistic> statistics = fsRepaymentStatisticService.selectFsRepaymentStatisticList(query);
        if (statistics.isEmpty()) {
            return error("无法找到统计信息，请联系管理员！");
        }
        FsRepaymentStatistic oldS = statistics.get(0);

        calendar.setTime(schedule.getJhrq());
        int nyear = calendar.get(Calendar.YEAR);
        int nmonth = calendar.get(Calendar.MONTH) + 1;
        if (year != nyear || month != nmonth) {
            query.setYear(nyear);
            query.setMonth(nmonth);
            statistics = fsRepaymentStatisticService.selectFsRepaymentStatisticList(query);
            if (statistics.isEmpty()) {
                FsRepaymentStatistic newS = new FsRepaymentStatistic();
                newS.setSsr(schedule.getSsr());
                newS.setYear(nyear);
                newS.setMonth(nmonth);
                newS.setDhnum(1);
                newS.setDhje(schedule.getJhje());
                fsRepaymentStatisticService.insertFsRepaymentStatistic(newS);
            } else {
                FsRepaymentStatistic newS = statistics.get(0);
                int dhnum = newS.getDhnum() + 1;
                BigDecimal dhje = newS.getDhje().add(schedule.getJhje());
                newS.setDhnum(dhnum);
                newS.setDhje(dhje);
                fsRepaymentStatisticService.updateFsRepaymentStatistic(newS);
            }
            int dhnum = oldS.getDhnum() - 1;
            BigDecimal dhje = oldS.getDhje().subtract(old.getJhje());
            oldS.setDhnum(dhnum);
            oldS.setDhje(dhje);
        } else {
            BigDecimal change = schedule.getJhje().subtract(old.getJhje());
            BigDecimal dhje = oldS.getDhje().add(change);
            oldS.setDhje(dhje);
        }
        BigDecimal change = schedule.getJhje().subtract(old.getJhje());
        BigDecimal zje = oldS.getZje().add(change);
        oldS.setZje(zje);
        fsRepaymentStatisticService.updateFsRepaymentStatistic(oldS);
        fsCaseRepaymentScheduleService.updateFsCaseRepaymentSchedule(schedule);
        return success();
    }

    /**
     * 删除还款计划
     */
    @PreAuthorize("@ss.hasPermi('fs:case:remove')")
    @Log(title = "还款计划", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fsCaseRepaymentScheduleService.deleteFsCaseRepaymentScheduleByIds(ids));
    }

    /**
     * 修改状态
     */
    @PreAuthorize("@ss.hasPermi('fs:case:query')")
    @GetMapping(value = "zt/{id}/{zt}")
    public AjaxResult changeZt(@PathVariable("id") Long id, @PathVariable("zt") Integer zt) {
        FsCaseRepaymentSchedule old = fsCaseRepaymentScheduleService.selectFsCaseRepaymentScheduleById(id);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(old.getJhrq());
        int year = calendar.get(Calendar.YEAR);
        int month = calendar.get(Calendar.MONTH) + 1;
        FsRepaymentStatistic statistic = new FsRepaymentStatistic();
        statistic.setSsr(old.getSsr());
        statistic.setYear(year);
        statistic.setMonth(month);
        List<FsRepaymentStatistic> statistics = fsRepaymentStatisticService.selectFsRepaymentStatisticList(statistic);
        if (statistics.isEmpty()) {
            return error("无法找到统计信息，请联系管理员！");
        }
        statistic = statistics.get(0);
        if (zt.intValue() != old.getZt().intValue()) {
            if (old.getZt().intValue() == 0) {
                //待还款-》逾期
                if (zt.intValue() == 3) {
                    int dhnum = statistic.getDhnum() - 1;
                    BigDecimal dhje = statistic.getDhje().subtract(old.getJhje());
                    int yqnum = statistic.getYqnum() + 1;
                    BigDecimal yqje = statistic.getYqje().add(old.getJhje());
                    statistic.setDhnum(dhnum);
                    statistic.setDhje(dhje);
                    statistic.setYqnum(yqnum);
                    statistic.setYqje(yqje);
                }
            }
            if (old.getZt().intValue() == 1) {
                //待审核-》待还款
                if (zt.intValue() == 0) {
                    int dhnum = statistic.getDhnum() + 1;
                    BigDecimal dhje = statistic.getDhje().add(old.getJhje());
                    int dshnum = statistic.getDshnum() - 1;
                    BigDecimal dshje = statistic.getDshje().subtract(old.getShje());
                    statistic.setDhnum(dhnum);
                    statistic.setDhje(dhje);
                    statistic.setDshnum(dshnum);
                    statistic.setDshje(dshje);
                }
                //待审核-》已审核
                if (zt.intValue() == 2) {
                    int dshnum = statistic.getDshnum() - 1;
                    BigDecimal dshje = statistic.getDshje().subtract(old.getShje());
                    int yhnum = statistic.getYhnum() + 1;
                    BigDecimal yhje = statistic.getYhje().add(old.getShje());
                    statistic.setDshnum(dshnum);
                    statistic.setDshje(dshje);
                    statistic.setYhnum(yhnum);
                    statistic.setYhje(yhje);
                }
            }
            if (old.getZt().intValue() == 3) {
                //逾期 -》待还款
                if (zt.intValue() == 0) {
                    int dhnum = statistic.getDhnum() + 1;
                    BigDecimal dhje = statistic.getDhje().add(old.getJhje());
                    int yqnum = statistic.getYqnum() - 1;
                    BigDecimal yqje = statistic.getYqje().subtract(old.getJhje());
                    statistic.setDhnum(dhnum);
                    statistic.setDhje(dhje);
                    statistic.setYqnum(yqnum);
                    statistic.setYqje(yqje);
                }
            }
        }
        fsRepaymentStatisticService.updateFsRepaymentStatistic(statistic);
        old.setZt(zt);
        fsCaseRepaymentScheduleService.updateFsCaseRepaymentSchedule(old);
        return success();
    }

    /**
     * 获取还款计划统计信息
     */
    @PreAuthorize("@ss.hasPermi('fs:case:query')")
    @GetMapping(value = "statistic/{year}/{month}")
    public AjaxResult getStatistic(@PathVariable("year") Integer year, @PathVariable("month") Integer month) {
        FsRepaymentStatistic query = new FsRepaymentStatistic();
        LoginUser loginUser = getLoginUser();
        SysUser user = loginUser.getUser();
        List<SysRole> roles = user.getRoles();
        List<Long> roleIds = new ArrayList<>();
        for (int i = 0; i < roles.size(); i++) {
            roleIds.add(roles.get(i).getRoleId());
        }
        if (roleIds.contains(1) || roleIds.contains(2)) {

        } else if (roleIds.contains(101L)) {
            query.setSsr(user.getUserId());
        }
        query.setYear(year);
        query.setMonth(month);
        List<FsRepaymentStatistic> statistics = fsRepaymentStatisticService.selectFsRepaymentStatisticList(query);
        Integer znum = 0;
        BigDecimal zje = BigDecimal.ZERO;
        Integer dhnum = 0;
        BigDecimal dhje = BigDecimal.ZERO;
        Integer dshnum = 0;
        BigDecimal dshje = BigDecimal.ZERO;
        Integer yhnum = 0;
        BigDecimal yhje = BigDecimal.ZERO;
        Integer yqnum = 0;
        BigDecimal yqje = BigDecimal.ZERO;
        if (!statistics.isEmpty()) {
            for (int i = 0; i < statistics.size(); i++) {
                FsRepaymentStatistic statistic = statistics.get(i);
                znum += statistic.getZnum();
                zje = zje.add(statistic.getZje());
                dhnum += statistic.getDhnum();
                dhje = dhje.add(statistic.getDhje());
                dshnum += statistic.getDshnum();
                dshje = dshje.add(statistic.getDshje());
                yhnum += statistic.getYhnum();
                yhje = yhje.add(statistic.getYhje());
                yqnum += statistic.getYqnum();
                yqje = yqje.add(statistic.getYqje());
            }
        }
        query.setZnum(znum);
        query.setZje(zje);
        query.setDhnum(dhnum);
        query.setDhje(dhje);
        query.setDshnum(dshnum);
        query.setDshje(dshje);
        query.setYhnum(yhnum);
        query.setYhje(yhje);
        query.setYqnum(yqnum);
        query.setYqje(yqje);
        return success(query);
    }
}
